package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SysEmailConfig;
import com.ruoyi.system.domain.SysEmailLog;
import com.ruoyi.system.service.ISysEmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 邮件配置Controller
 */
@RestController
@RequestMapping("/system/email")
public class SysEmailController extends BaseController {
    @Autowired
    private ISysEmailService emailService;

    /**
     * 获取邮件配置列表
     */
    @PreAuthorize("@ss.hasPermi('system:email:list')")
    @GetMapping("/config/list")
    public TableDataInfo configList(SysEmailConfig config) {
        startPage();

        List<SysEmailConfig> list = emailService.selectSysEmailConfigList(config);
        return getDataTable(list);
    }

    /**
     * 导出邮件配置列表
     */
    @PreAuthorize("@ss.hasPermi('system:email:export')")
    @Log(title = "邮件配置", businessType = BusinessType.EXPORT)
    @PostMapping("/config/export")
    public void configExport(HttpServletResponse response, SysEmailConfig config) {
        List<SysEmailConfig> list = emailService.selectSysEmailConfigList(config);
        ExcelUtil<SysEmailConfig> util = new ExcelUtil<>(SysEmailConfig.class);
        util.exportExcel(response, list, "邮件配置数据");
    }

    /**
     * 获取邮件配置详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:email:query')")
    @GetMapping(value = "/config/{configId}")
    public AjaxResult getConfig(@PathVariable("configId") Long configId) {
        return AjaxResult.success(emailService.selectSysEmailConfigById(configId));
    }

    /**
     * 新增邮件配置
     */
    @PreAuthorize("@ss.hasPermi('system:email:add')")
    @Log(title = "邮件配置", businessType = BusinessType.INSERT)
    @PostMapping("/config")
    public AjaxResult addConfig(@Validated @RequestBody SysEmailConfig config) {
        return toAjax(emailService.insertSysEmailConfig(config));
    }

    /**
     * 修改邮件配置
     */
    @PreAuthorize("@ss.hasPermi('system:email:edit')")
    @Log(title = "邮件配置", businessType = BusinessType.UPDATE)
    @PutMapping("/config")
    public AjaxResult updateConfig(@Validated @RequestBody SysEmailConfig config) {
        return toAjax(emailService.updateSysEmailConfig(config));
    }

    /**
     * 删除邮件配置
     */
    @PreAuthorize("@ss.hasPermi('system:email:remove')")
    @Log(title = "邮件配置", businessType = BusinessType.DELETE)
    @DeleteMapping("/config/{configId}")
    public AjaxResult removeConfig(@PathVariable Long configId) {
        return toAjax(emailService.deleteSysEmailConfigById(configId));
    }

    /**
     * 获取邮件发送日志列表
     */
    @PreAuthorize("@ss.hasPermi('system:email:list')")
    @GetMapping("/log/list")
    public TableDataInfo logList(SysEmailLog log) {
        startPage();
        List<SysEmailLog> list = emailService.selectSysEmailLogList(log);
        return getDataTable(list);
    }

    /**
     * 导出邮件发送日志列表
     */
    @PreAuthorize("@ss.hasPermi('system:email:export')")
    @Log(title = "邮件日志", businessType = BusinessType.EXPORT)
    @PostMapping("/log/export")
    public void logExport(HttpServletResponse response, SysEmailLog log) {
        List<SysEmailLog> list = emailService.selectSysEmailLogList(log);
        ExcelUtil<SysEmailLog> util = new ExcelUtil<>(SysEmailLog.class);
        util.exportExcel(response, list, "邮件发送日志");
    }

    /**
     * 发送简单邮件
     */
    @PreAuthorize("@ss.hasPermi('system:email:send')")
    @Log(title = "发送邮件", businessType = BusinessType.OTHER)
    @PostMapping("/send/simple")
    public AjaxResult sendSimpleEmail(@RequestParam String to,
                                    @RequestParam String subject,
                                    @RequestParam String content) {
        return toAjax(emailService.sendSimpleMail(null, to, subject, content));
    }

    /**
     * 发送HTML邮件
     */
    @PreAuthorize("@ss.hasPermi('system:email:send')")
    @Log(title = "发送邮件", businessType = BusinessType.OTHER)
    @PostMapping("/send/html")
    public AjaxResult sendHtmlEmail(@RequestParam String to,
                                  @RequestParam String subject,
                                  @RequestParam String content) {
        return toAjax(emailService.sendHtmlMail(null, to, subject, content));
    }

    /**
     * 发送带附件的邮件
     */
    @PreAuthorize("@ss.hasPermi('system:email:send')")
    @Log(title = "发送邮件", businessType = BusinessType.OTHER)
    @PostMapping("/send/attachment")
    public AjaxResult sendAttachmentEmail(@RequestParam String to,
                                        @RequestParam String subject,
                                        @RequestParam String content,
                                        @RequestParam("files") MultipartFile[] files) {
        List<File> attachments = new ArrayList<>();
        try {
            for (MultipartFile file : files) {
                File tempFile = File.createTempFile("email_", "_" + file.getOriginalFilename());
                file.transferTo(tempFile);
                tempFile.deleteOnExit();
                attachments.add(tempFile);
            }
            return toAjax(emailService.sendAttachmentsMail(null, to, subject, content, attachments));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }
} 